// websocket.ts
import { Ref, ref } from 'vue';

// 定义消息类型接口
export interface WebSocketMessage {
    type: string;
    content: string;
    [key: string]: any; // 允许其他自定义字段
}

// 定义WebSocket状态类型
type WebSocketStatus = 'CONNECTING' | 'OPEN' | 'CLOSING' | 'CLOSED';

class WebSocketService {
    private websocket: WebSocket | null = null;
    private status: Ref<WebSocketStatus> = ref('CLOSED');
    private receivedMessages: Ref<WebSocketMessage[]> = ref([]);

    // 获取当前连接状态
    get connectionStatus(): Ref<WebSocketStatus> {
        return this.status;
    }

    // 获取接收的消息列表
    get messages(): Ref<WebSocketMessage[]> {
        return this.receivedMessages;
    }

    // 初始化WebSocket连接
    initWebSocket(userId: string): void {
        if ('WebSocket' in window) {
            // 关闭已有连接
            if (this.websocket) {
                this.closeWebSocket();
            }

            try {
                const url = `ws://localhost:8080/boke/websocket/${userId}`;
                this.websocket = new WebSocket(url);
                this.status.value = 'CONNECTING';

                // 连接建立成功
                this.websocket.onopen = () => {
                    console.log('WebSocket连接成功');
                    this.status.value = 'OPEN';
                };

                // 接收消息
                this.websocket.onmessage = (event) => {
                    console.log('收到消息:', event.data);
                    try {
                        // 尝试解析为JSON
                        const parsedMessage: WebSocketMessage = JSON.parse(event.data);
                        this.receivedMessages.value.push(parsedMessage);
                    } catch (error) {
                        // 如果不是JSON格式，作为普通文本处理
                        this.receivedMessages.value.push({
                            type: 'text',
                            content: event.data
                        });
                    }
                };

                // 连接关闭
                this.websocket.onclose = () => {
                    console.log('WebSocket连接关闭');
                    this.status.value = 'CLOSED';
                    // 3秒后自动重连
                    setTimeout(() => this.initWebSocket(userId), 3000);
                };

                // 连接错误
                this.websocket.onerror = (error) => {
                    console.error('WebSocket发生错误:', error);
                };

                // 窗口关闭时主动关闭连接
                window.addEventListener('beforeunload', () => {
                    this.closeWebSocket();
                });
            } catch (error) {
                console.error('初始化WebSocket失败:', error);
            }
        } else {
            alert('当前浏览器不支持WebSocket协议，无法使用实时功能');
        }
    }

    // 关闭WebSocket连接
    closeWebSocket(): void {
        if (this.websocket) {
            this.websocket.close();
            this.websocket = null;
            this.status.value = 'CLOSED';
        }
    }

    // 发送消息
    sendMessage(message: WebSocketMessage | string): boolean {
        if (this.websocket && this.status.value === 'OPEN') {
            try {
                const messageStr = typeof message === 'string' ? message : JSON.stringify(message);
                this.websocket.send(messageStr);
                return true;
            } catch (error) {
                console.error('发送消息失败:', error);
                return false;
            }
        } else {
            console.error('WebSocket连接未建立或已关闭，无法发送消息');
            return false;
        }
    }
}

// 导出单例实例
export const webSocketService = new WebSocketService();
